package com.itheima.project.service.serviceImpI;

import com.itheima.project.entity.User;
import com.itheima.project.entity.UserAuth;
import com.itheima.project.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author     ：zhangheng
 * @date       ：Created in 2024/9/7 18:10
 * @description：调用数据库1.0
 * @modified By：
 * @version:
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据前端传递过来的username查找调用mapper查询数据库用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名不存在或以被禁用");
        }
        UserAuth userAuth = new UserAuth();
        userAuth.setUsername(user.getUsername());
        userAuth.setUsername(user.getPassword());
        userAuth.setUsername(user.getNickName());

        //2.封装用户的角色角色集合（不写死user,admin角色信息）
        List<String> roleList = new ArrayList<>();
        //3.封装springsecurity的User对象（UserDetails接口的实现类）
        //用户是user@qq.com，配置角色user
        if ("user@qq.com".equals(username)) {
            roleList.add("USER");
            userAuth.setRoles(roleList);
        } else {
            //用户是user@qq.com，配置角色user,admin
            roleList.add("USER");
            roleList.add("ADMIN");
            userAuth.setRoles(roleList);
        }

        return userAuth;

    }
}

